package com.xxmw.transaction.controller;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xxmw.transaction.common.entity.P;
import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.common.utils.Constant;
import com.xxmw.transaction.model.SysRole;
import com.xxmw.transaction.service.SysRoleMenuService;
import com.xxmw.transaction.service.SysRoleService;

@RestController
@RequestMapping("/admin/role")
public class SysRoleController extends BaseController {

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysRoleMenuService sysRoleMenuServcie;

	@GetMapping("/list")
	@RequiresPermissions("system:role:list")
	public R list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
			@RequestParam(required = false) String roleName) {
		P<SysRole> p = sysRoleService.getList(pageNum, pageSize, roleName, getUserId() == Constant.SUPER_ADMIN ? null :  getUserId());
		return R.ok(p);
	}

	@GetMapping("/select")
	@RequiresPermissions("system:role:list")
	public R select() {
		Map<String, Object> map = new HashMap<>();
		if(getUserId() != Constant.SUPER_ADMIN) {
			map.put("create_user_id", getUserId());
		}
		Collection<SysRole> collection = sysRoleService.listByMap(map);
		return R.ok(collection);
	}

	@GetMapping("/info/{roleId}")
	@RequiresPermissions("system:role:info")
	public R info(@PathVariable("roleId") Long roleId) {
		SysRole sysRole = sysRoleService.getById(roleId);
		List<Long> menuIdList = sysRoleMenuServcie.getMenuIdList(roleId);
		sysRole.setMenuIdList(menuIdList);
		return R.ok(sysRole);
	}

	@PostMapping("/saveOrUpdate")
	@RequiresPermissions(value = {"system:role:update", "system:role:save"}, logical = Logical.OR)
	public R saveOrUpdate(@RequestBody SysRole role){
		role.setAdder(getUserId());
		sysRoleService.addOrUpdate(role);
		return R.ok();
	}

	@PostMapping("/delete")
	@RequiresPermissions("system:role:delete")
	public R delete(@RequestBody Long[] roleIds){
		sysRoleService.deleteBatch(roleIds);
		return R.ok();
	}
}
